package com.tnsw.facebookautoliker.helper.command;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.Context;
import android.os.AsyncTask;

import com.tnsw.coreutils.MyLog;
import com.tnsw.coreutils.http.THttpBase;
import com.tnsw.coreutils.http.THttpGet;
import com.tnsw.coreutils.http.THttpListener;
import com.tnsw.facebookautoliker.database.DBManager;
import com.tnsw.facebookautoliker.helper.FacebookBGManager;
import com.tnsw.facebookautoliker.helper.FacebookCommandObject;
import com.tnsw.facebookautoliker.helper.GeneralManager;

public class GetHTTPPhoto extends FacebookCommandObject implements THttpListener {

	private String tag = "GetHTTPPhoto";
	private String url;
	
	private DBManager dbm;
	private FacebookBGManager fbm;
	private GeneralManager gm;
	private String photoPath = "";
	
	private THttpGet httpFirst;
	private THttpGet httpImage;
	private String extension = "";
	private String filename = "";
	
	private String signature;
	
	public GetHTTPPhoto(Context context, String url, String filename) {
		super(context);
		MyLog.d(tag, "GetHTTPPhoto(url=" + url + ", filename=" + filename + ")");
		this.url = url;
		this.filename = filename;
		this.signature = this.getClass().getName() + "_" + url;
		
		this.dbm = DBManager.getInstance(context);
		this.fbm = FacebookBGManager.getInstance(context);
		this.gm = GeneralManager.getInstance();
		
		this.setRequiredSignature(true);
	}
	
	private void prepareHeader(THttpBase http, String url) {

		http.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		http.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
		http.addHeader("Accept-Encoding", "gzip,deflate,sdch");
		http.addHeader("Connection", "keep-alive");
		http.addHeader("Accept-Language", "th,en-US;q=0.8,en;q=0.6");
		http.addHeader("Host", THttpBase.getHost2(url));
		http.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4");
		http.setListener(this);
		
	}
	
	@Override
	public String getSignature() {
		return(this.signature);
	}
	
	public String getPhotoPath() {
		return(this.photoPath);
	}
	
	@Override
	public void execute() {
		super.execute();
		
		MyLog.d(tag, "Starting httpFirst");
		this.httpFirst = new THttpGet(context, url);
		
		HttpClient client = new DefaultHttpClient();
		client.getParams().setParameter("http.protocol.handle-redirects", false);
		this.httpFirst.setHttpClient(client);
		this.httpFirst.setSessionName("metadata");
		this.httpFirst.setBinaryDirection(THttpBase.BINARY_TO_FILE);
		
		this.prepareHeader(this.httpFirst, url);
		this.httpFirst.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");		
	}
	
	@Override
	public void onProgressUpdate(THttpBase sender, Integer[] values) {
		
	}

	@Override
	public void onPostExecute(THttpBase sender, Long result) {
		if (sender == this.httpFirst) {
			if (result == 0l) {
				MyLog.d(tag, "HttpStatus=" + sender.getHttpResponse().getStatusLine().getStatusCode());
				if (sender.getHttpResponse().getStatusLine().getStatusCode() == 302) {
					String url = sender.getHttpResponse().getHeaders("Location")[0].getValue();
					
					MyLog.d(tag, "Starting httpImage");
					this.httpImage = new THttpGet(context, url);
					this.httpImage.setBinaryDirection(THttpBase.BINARY_TO_FILE);
					this.httpImage.setSessionName("image");
					this.prepareHeader(this.httpImage, url);
					this.httpImage.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "0");
					
				} else if (sender.getHttpResponse().getStatusLine().getStatusCode() == 200) {
					// Not redirect, I believed I got binary
					MyLog.d(tag, "?photo_path=" + sender.getCurrentBinaryfileName());
					this.photoPath = sender.getCurrentBinaryfileName();
					this.fbm.updateCommandStatus(this, 200, null);
				}
				
			} else {
				this.fbm.updateCommandStatus(this, 400, sender.getLatestException());
			}
			
		} else if (sender == this.httpImage) {
			if (result == 0l) {
				this.photoPath = sender.getCurrentBinaryfileName();
				this.fbm.updateCommandStatus(this, 200, null);
			} else {
				this.fbm.updateCommandStatus(this, 401, sender.getLatestException());
			}
		}
	}

	@Override
	public void onNewLineFetchBG(THttpBase sender, String line) {
		
	}

	@Override
	public void onReceiveResponseBG(THttpBase sender) {
		
	}

	@Override
	public void onBinaryReadBG(THttpBase sender, byte[] b) {
		
	}

	@Override
	public void interceptHandler(THttpBase sender) {
		
		try {
			if (sender.getSessionName().equals("metadata")) {
				String contentType = sender.getHttpResponse().getFirstHeader("Content-Type").getValue();
				this.extension = contentType.split("/")[1];
				MyLog.d(tag, "extension=" + this.extension);
				if (this.extension.equals("jpeg")) {
					this.extension = "jpg";
					MyLog.d(tag, "change extension to '" + this.extension + "'");
				
				}
				
				sender.setPredefinedFileName(this.filename + "." + this.extension);
				sender.setPredefinedExtension(this.extension);
				
			} else if (sender.getSessionName().equals("image")) {
				sender.setPredefinedExtension(this.extension);
				String filename = this.filename + "." + this.extension;
				sender.setPredefinedFileName(filename);
			}
		} catch (Exception e) {
			MyLog.e(tag, "interceptHandler(session=" + sender.getSessionName() + ") - " + e.toString(), e);
		}

	}



}
